<template>
  <div class="tts-container">
    <h1>语音合成</h1>
    <div class="input-section">
      <textarea
        v-model="text"
        placeholder="请输入要合成的文本内容"
        rows="4"
      ></textarea>
      <button @click="generateSpeech" :disabled="!text || isLoading">
        {{ isLoading ? '生成中...' : '生成语音' }}
      </button>
    </div>
    <div v-if="audioUrl" class="audio-section">
      <audio controls :src="audioUrl"></audio>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const text = ref('')
const audioUrl = ref('')
const isLoading = ref(false)

const generateSpeech = async () => {
  if (!text.value) return
  
  isLoading.value = true
  try {
    const encodedText = encodeURIComponent(text.value)
    const response = await fetch(`http://127.0.0.1:9882/kokoro?text=${encodedText}`, {
      method: 'GET'
    })

    const blob = await response.blob()
    audioUrl.value = URL.createObjectURL(blob)
  } catch (error) {
    console.error('语音生成失败:', error)
    alert('语音生成失败，请重试')
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.tts-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 2rem;
}

.input-section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 2rem;
}

textarea {
  width: 100%;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  resize: vertical;
}

button {
  padding: 0.8rem 2rem;
  background-color: #42b883;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #3aa876;
}

button:disabled {
  background-color: #a8a8a8;
  cursor: not-allowed;
}

.audio-section {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}

audio {
  width: 100%;
  max-width: 500px;
}
</style>

